/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.logistics.web.customsdeclaration;

import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.financial.entity.declarationnotice.TdeclarationNotice;
import com.jeesite.modules.financial.entity.declarationnotice.TdeclarationNoticeDetail;
import com.jeesite.modules.financial.entity.lettercredit.LetterCredit;
import com.jeesite.modules.financial.service.declarationnotice.TdeclarationNoticeService;
import com.jeesite.modules.financial.service.lettercredit.LetterCreditService;
import com.jeesite.modules.logistics.entity.customsdeclaration.CustomsDeclaration;
import com.jeesite.modules.logistics.entity.customsdeclaration.CustomsDeclarationDetail;
import com.jeesite.modules.logistics.service.customsdeclaration.CustomsDeclarationService;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 报关Controller
 *
 * @author LV
 * @version 2021-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/logistics/customsdeclaration/customsDeclaration")
public class CustomsDeclarationController extends BaseController {

    @Autowired
    private CustomsDeclarationService customsDeclarationService;
    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private TdeclarationNoticeService declarationNoticeService;
    @Autowired
    private LetterCreditService letterCreditService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private TcarService carService;


    /**
     * 获取数据
     */
    @ModelAttribute
    public CustomsDeclaration get(String customsDeclarationId, boolean isNewRecord) {
        return customsDeclarationService.get(customsDeclarationId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:view")
    @RequestMapping(value = {"list", ""})
    public String list(CustomsDeclaration customsDeclaration, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        model.addAttribute("customsDeclaration", customsDeclaration);
        return "modules/logistics/customsdeclaration/customsDeclarationList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<CustomsDeclaration> listData(CustomsDeclaration customsDeclaration, HttpServletRequest request, HttpServletResponse response) {
        customsDeclaration.setPage(new Page<>(request, response));
        Page<CustomsDeclaration> page = customsDeclarationService.findPage(customsDeclaration);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:view")
    @RequestMapping(value = "form")
    public String form(CustomsDeclaration customsDeclaration, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("listDeclarationNotice", declarationNoticeService.findList(new TdeclarationNotice())); // 报关通知单
        model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));
        model.addAttribute("lictCar", carService.findList(new Tcar()));
        for (CustomsDeclarationDetail detail : customsDeclaration.getCustomsDeclarationDetailList()) {
            detail.setCarName(detail.getTcar().getCarName());
            detail.setComprehensiveTax1(detail.getComprehensiveTax());
            detail.setTaxPriceF1(detail.getTaxPriceF());
        }
        model.addAttribute("customsDeclaration", customsDeclaration);
        return "modules/logistics/customsdeclaration/customsDeclarationForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:view")
    @RequestMapping(value = "detail")
    public String detail(CustomsDeclaration customsDeclaration, Model model) {
        // 明细合计
        Double foreignCurrencyPrice1 = 0D;
        Double declaredPrice1 = 0D;
        Double taxPrice1 = 0D;
        Double importDuty1 = 0D;
        Double importConsumptionTax1 = 0D;
        Double importVat1 = 0D;
        Double comprehensiveTax1 = 0D;
        Double taxAmount1 = 0D;
        List<CustomsDeclarationDetail> customsDeclarationDetailList = customsDeclaration.getCustomsDeclarationDetailList();
        for (CustomsDeclarationDetail detail : customsDeclarationDetailList) {
            foreignCurrencyPrice1 = NumberUtils.add(foreignCurrencyPrice1,detail.getForeignCurrencyPrice() == null ? 0 :detail.getForeignCurrencyPrice());
            declaredPrice1 = NumberUtils.add(declaredPrice1,detail.getDeclaredPrice() == null ? 0 :detail.getDeclaredPrice());
            taxPrice1 = NumberUtils.add(taxPrice1,detail.getTaxPrice() == null ? 0 :detail.getTaxPrice());
            importDuty1 = NumberUtils.add(importDuty1,detail.getImportDuty() == null ? 0 :detail.getImportDuty());
            importConsumptionTax1 = NumberUtils.add(importConsumptionTax1,detail.getImportConsumptionTax() == null ? 0 :detail.getImportConsumptionTax());
            importVat1 = NumberUtils.add(importVat1,detail.getImportVat() == null ? 0 :detail.getImportVat());
            comprehensiveTax1 = NumberUtils.add(comprehensiveTax1,detail.getComprehensiveTax() == null ? 0 :detail.getComprehensiveTax());
            taxAmount1 = NumberUtils.add(taxAmount1,detail.getTaxAmount() == null ? 0 :detail.getTaxAmount());
            detail.setCarName(detail.getTcar().getCarName());
        }
        customsDeclaration.setForeignCurrencyPrice1(foreignCurrencyPrice1);
        customsDeclaration.setDeclaredPrice1(declaredPrice1);
        customsDeclaration.setTaxPrice1(taxPrice1);
        customsDeclaration.setImportDuty1(importDuty1);
        customsDeclaration.setImportConsumptionTax1(importConsumptionTax1);
        customsDeclaration.setImportVat1(importVat1);
        customsDeclaration.setComprehensiveTax1(comprehensiveTax1);
        customsDeclaration.setTaxAmount1(taxAmount1);

        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("listDeclarationNotice", declarationNoticeService.findList(new TdeclarationNotice())); // 报关通知单
        model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));
        model.addAttribute("lictCar", carService.findList(new Tcar()));
        model.addAttribute("customsDeclaration", customsDeclaration);
        return "modules/logistics/customsdeclaration/customsDeclarationDetail";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated CustomsDeclaration customsDeclaration) {
        customsDeclarationService.save(customsDeclaration);
        return renderResult(Global.TRUE, text("保存报关成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(CustomsDeclaration customsDeclaration) {
        customsDeclarationService.delete(customsDeclaration);
        return renderResult(Global.TRUE, text("删除报关成功！"));
    }

    /**
     * 列表选择对话框
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:view")
    @RequestMapping(value = "customsDeclarationSelect")
    public String empUserSelect(CustomsDeclaration customsDeclaration, String selectData, Model model) {
        String selectDataJson = EncodeUtils.decodeUrl(selectData);
        if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()) {
            model.addAttribute("selectData", selectDataJson);
        }
        model.addAttribute("CustomsDeclaration", customsDeclaration);
        return "modules/logistics/customsdeclaration/customsDeclarationSelect";
    }

    /**
     * 创建自 报关通知单
     */
    @RequiresPermissions("logistics:customsdeclaration:customsDeclaration:view")
    @RequestMapping(value = "createFromDeclaration")
    public String createFromDeclaration(TdeclarationNotice tdeclarationNotice, Model model) {
        TdeclarationNotice declarationNotice = declarationNoticeService.get(tdeclarationNotice.getCustomsDeclarationNoticeId());
        if (StringUtils.isNotEmpty(declarationNotice.getServiceOrderId())) {
            CustomsDeclaration customsDeclaration = new CustomsDeclaration();
            ServiceOrder serviceOrder = serviceOrderService.get(declarationNotice.getServiceOrderId());
            customsDeclaration.setServiceOrderId(declarationNotice.getServiceOrderId());
            customsDeclaration.setCustomerId(declarationNotice.getCustomerId());
            customsDeclaration.setLetterCreditCode(serviceOrder.getLetterCreditCode());
            customsDeclaration.setCurrency(serviceOrder.getCurrency());
            customsDeclaration.setInvestorId(serviceOrder.getInvestorId());
            customsDeclaration.setCustomsDeclarationNoticeCode(declarationNotice.getCustomsDeclarationNoticeId());
            customsDeclaration.setCustomsBroker(declarationNotice.getCustomsBroker());

            List<CustomsDeclarationDetail> customsDeclarationDetailList = ListUtils.newArrayList();
            List<TdeclarationNoticeDetail> declarationNoticeDetailList = declarationNotice.getTdeclarationNoticeDetailList();
            List<ServiceOrderDetail> serviceOrderDetailList = serviceOrder.getServiceOrderDetailList();
            for (TdeclarationNoticeDetail noticeDetail : declarationNoticeDetailList) {
                for (ServiceOrderDetail orderDetail : serviceOrderDetailList) {
                    if (StringUtils.isNotEmpty(noticeDetail.getFrameNumber()) && noticeDetail.getFrameNumber().equals(orderDetail.getFrameNumber())) {
                        CustomsDeclarationDetail customsDeclarationDetail = new CustomsDeclarationDetail();
                        customsDeclarationDetail.setFrameNumber(orderDetail.getFrameNumber());
                        customsDeclarationDetail.setCarId(orderDetail.getCarId());
                        customsDeclarationDetail.setCarName(orderDetail.getTcar().getCarName());
                        customsDeclarationDetail.setForeignCurrencyPrice(orderDetail.getUnitPrice());
                        //增加行号
                        customsDeclarationDetail.setRowNumber(orderDetail.getRowNumber());
                        customsDeclarationDetailList.add(customsDeclarationDetail);
                    }
                }
            }
            customsDeclaration.setCustomsDeclarationDetailList(customsDeclarationDetailList);

            model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
            model.addAttribute("listCustomer", customerService.findList(new Customer()));
            model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
            model.addAttribute("listDeclarationNotice", declarationNoticeService.findList(new TdeclarationNotice())); // 报关通知单
            model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));
            model.addAttribute("lictCar", carService.findList(new Tcar()));
            model.addAttribute("customsDeclaration", customsDeclaration);
            return "modules/logistics/customsdeclaration/customsDeclarationForm";
        } else {
            return renderResult(Global.FALSE, text("未查找到服务订单的相关信息！"));
        }
    }
}
